package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.JsonMapper;
import com.dongjiantong.common.utils.JsonUtil;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsDiagnosisMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsDiagnosis;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.service.FarmRecordsDiagnosisService;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.sys.service.SysLogsService;
import com.dongjiantong.user.enums.FarmsEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 防疫中心 -- 诊疗记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsDiagnosisServiceImpl extends ServiceMybatis<FarmRecordsDiagnosis> implements FarmRecordsDiagnosisService {
    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();

    @Resource
    private FarmRecordsDiagnosisMapper farmRecordsDiagnosisMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Resource
    private FarmRecordsFileService farmRecordsFileService;

    @Reference(version = "1.0.0")
    private SysLogsService sysLogsService;

    /**
     * 按条件查询(不包含牛)
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDiagnosis> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsDiagnosisMapper == null){
                throw new OPServerException("farmRecordsDiagnosisMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsDiagnosis> farmRecordsDiagnosisList = farmRecordsDiagnosisMapper.selectByMap(map);

            if (farmRecordsDiagnosisList.size() > 0){
                this.setPicOrVideoList(farmRecordsDiagnosisList);
            }

            return new PageInfo<FarmRecordsDiagnosis>(farmRecordsDiagnosisList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 获取关联信息(视频,图片)
     * @param farmRecordsDiagnosisList
     */
    public void setPicOrVideoList(List<FarmRecordsDiagnosis> farmRecordsDiagnosisList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }

        //获取记录id
        List<Long> ids = farmRecordsDiagnosisList.stream().map(farmRecordsDiagnosis -> farmRecordsDiagnosis.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.DIAGNOSIS.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsDiagnosis farmRecordsDiagnosis : farmRecordsDiagnosisList){
                this.setPicOrVideoByObject(farmRecordsDiagnosis,farmRecordsFileList);
            }
        }
    }

    /**
     * 放入图片 视频到对象中
     * @param farmRecordsDiagnosis
     * @param farmRecordsFileList
     */
    @Override
    public FarmRecordsDiagnosis setPicOrVideoByObject(FarmRecordsDiagnosis farmRecordsDiagnosis, List<FarmRecordsFile> farmRecordsFileList) {
        List<String> picList = null;
        List<String> videoList = null;
        for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
            if ((farmRecordsDiagnosis.getId()).equals(farmRecordsFile.getRelevance_id())){
                //获取图片
                if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    picList = list;
                }
                //获取视频
                if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    videoList = list;
                }
            }
        }
        //设置图片
        if (picList != null && picList.size() > 0){
            farmRecordsDiagnosis.setPicList(picList);
        }
        //设置视频
        if (videoList != null && videoList.size() > 0){
            farmRecordsDiagnosis.setVideoList(videoList);
        }

        return farmRecordsDiagnosis;
    }

    /**
     * 按条件查询(牛)
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDiagnosis> selectBullByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsDiagnosisMapper == null){
                throw new OPServerException("farmRecordsDiagnosisMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsDiagnosis> list = farmRecordsDiagnosisMapper.selectByMap(map);

            if (list.size() > 0){
                this.setPicOrVideoList(list);
            }

            return new PageInfo<FarmRecordsDiagnosis>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端按照单据状态分页查询列表
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDiagnosis> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId,Integer nonBull) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null){
            map.put("status",status);
        }
        map.put("farm_id",farmId);

        map.put("animal_second_non_bull",nonBull);

        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsDiagnosis> farmRecordsDiagnosisList = farmRecordsDiagnosisMapper.selectListByStatus(map);

        if (farmRecordsDiagnosisList.size() > 0){
            this.setPicOrVideoList(farmRecordsDiagnosisList);
        }

        return new PageInfo<FarmRecordsDiagnosis>(farmRecordsDiagnosisList);
    }

    /**
     * 根据关联牛档案id 查询对应的诊疗记录
     * @param cowRecordId
     * @return
     */
    @Override
    public List<FarmRecordsDiagnosis> selectBullDiagnosis(Long cowRecordId) {
        Map<String,Object> map = Maps.newHashMap();
        map.put("cow_record_id",cowRecordId);

        List<FarmRecordsDiagnosis> farmRecordsDiagnosisList = farmRecordsDiagnosisMapper.selectListCow(map);

        if (farmRecordsDiagnosisList.size() > 0) {
            this.setPicOrVideoList(farmRecordsDiagnosisList);
        }

        return farmRecordsDiagnosisList;
    }

    /**
     * 根据牛档案关联单据Ids 查询诊疗次数
     * @param ids
     * @return
     */
    @Override
    public List<Map<String, Object>> selectDiagnosisCount(List<Long> ids) {
        Map<String,Object> map = Maps.newHashMap();
        map.put("ids",ids);
        List<Map<String, Object>> result = farmRecordsDiagnosisMapper.selectDiagnosisCount(map);
        return result;
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsDiagnosis
     * @param loginInfo
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsDiagnosis farmRecordsDiagnosis, Integer toStatus) {
        if (farmRecordsDiagnosisMapper == null){ throw new OPServerException("farmRecordsDiagnosisMapper 为null,请检查"); }

        try {
            Integer fromStatus = farmRecordsDiagnosis.getStatus();
            //操作前的数据
            String before = JsonUtil.toJsonString(farmRecordsDiagnosis);

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "FZL";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsDiagnosisMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsDiagnosis.setNumber(number);

            farmRecordsDiagnosis.setProvince_id(loginInfo.getProvinceId());
            farmRecordsDiagnosis.setCity_id(loginInfo.getCityId());
            farmRecordsDiagnosis.setRegion_id(loginInfo.getRegionId());
            farmRecordsDiagnosis.setStreet_id(loginInfo.getStreetId());
            farmRecordsDiagnosis.setVillage_id(loginInfo.getVillageId());

            farmRecordsDiagnosis.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //todo 单据从状态到状态
            if (fromStatus == 0 && toStatus == null){
                //直接暂存
                farmRecordsDiagnosisMapper.createOne(farmRecordsDiagnosis);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)){
                //直接提交
                farmRecordsDiagnosis.setStatus(toStatus);
                farmRecordsDiagnosisMapper.createOne(farmRecordsDiagnosis);
            }

            if (farmRecordsDiagnosis.getId() != null) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DIAGNOSIS.getCode(),farmRecordsDiagnosis.getPicList(),farmRecordsDiagnosis.getVideoList(),farmRecordsDiagnosis.getId());
            }

            //操作后的数据
            String ofter = JsonUtil.toJsonString(farmRecordsDiagnosis);
            //当前登录人
            Long userId = UserUtil.getUserId();
            //todo 生成日志记录
            //sysLogsService.createLogs(LogsEnum.ADD,FarmRecordsTableEnum.FARM_RECORDS_DIAGNOSIS.getTableName(),farmRecordsDiagnosis.getId().toString(),before,ofter,userId);

            return farmRecordsDiagnosis.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 新增牛档案诊疗记录
     * @param loginInfo
     * @param farmRecordsDiagnosis
     * @param toStatus
     * @return
     */
    @Override
    public Long createBullOne(LoginInfo loginInfo, FarmRecordsDiagnosis farmRecordsDiagnosis, Integer toStatus) {
        try {
            Integer fromStatus = farmRecordsDiagnosis.getStatus();
            //操作前的数据
            String before = JsonUtil.toJsonString(farmRecordsDiagnosis);

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "FZL";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsDiagnosisMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsDiagnosis.setNumber(number);

            farmRecordsDiagnosis.setProvince_id(loginInfo.getProvinceId());
            farmRecordsDiagnosis.setCity_id(loginInfo.getCityId());
            farmRecordsDiagnosis.setRegion_id(loginInfo.getRegionId());
            farmRecordsDiagnosis.setStreet_id(loginInfo.getStreetId());
            farmRecordsDiagnosis.setVillage_id(loginInfo.getVillageId());

            farmRecordsDiagnosis.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            if (fromStatus == null) {
                throw new OPServerException("对象状态为null");
            }

            //todo 单据从状态到状态
            if (fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)){
                //直接提交
                farmRecordsDiagnosis.setStatus(toStatus);
                farmRecordsDiagnosisMapper.createOne(farmRecordsDiagnosis);
            }

            if (farmRecordsDiagnosis.getId() != null) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DIAGNOSIS.getCode(),farmRecordsDiagnosis.getPicList(),farmRecordsDiagnosis.getVideoList(),farmRecordsDiagnosis.getId());
            }

            //操作后的数据
            String ofter = JsonUtil.toJsonString(farmRecordsDiagnosis);
            //当前登录人
            Long userId = UserUtil.getUserId();
            //todo 生成日志记录
            //sysLogsService.createLogs(LogsEnum.ADD,FarmRecordsTableEnum.FARM_RECORDS_DIAGNOSIS.getTableName(),farmRecordsDiagnosis.getId().toString(),before,ofter,userId);

            return farmRecordsDiagnosis.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsDiagnosis
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsDiagnosis farmRecordsDiagnosis, Integer toStatus) {
        try {
            if (farmRecordsDiagnosisMapper == null){
                throw new OPServerException("farmRecordsDiagnosisMapper 为null,请检查");
            }

            FarmRecordsDiagnosis before = farmRecordsDiagnosisMapper.selectByPrimaryKey(farmRecordsDiagnosis);
            //生成操作前的json数据
            String beforeJson = JsonUtil.toJsonString(before);

            farmRecordsDiagnosis.setStatus(toStatus);
            farmRecordsDiagnosis.setUpdated_at(new Date());
            //todo 更新单据
            int con = farmRecordsDiagnosisMapper.updateByPrimaryKeySelective(farmRecordsDiagnosis);

            //todo 更新图片视频
            List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileService.selectPicOrVideoListByRelevanceIds(Lists.newArrayList(farmRecordsDiagnosis.getId()),FarmRecordsFileEnum.DIAGNOSIS.getCode(),Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode()));

            if (farmRecordsFileList.size() > 0) {
                farmRecordsFileService.updatePicOrVideoByRelevanceId(FarmRecordsFileEnum.DIAGNOSIS.getCode(),farmRecordsDiagnosis.getPicList(),farmRecordsDiagnosis.getVideoList(),farmRecordsDiagnosis.getId());
            } else {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DIAGNOSIS.getCode(),farmRecordsDiagnosis.getPicList(),farmRecordsDiagnosis.getVideoList(),farmRecordsDiagnosis.getId());
            }

            /*//生成操作后的json数据
            String afterJson = JsonUtil.toJsonString(farmRecordsDiagnosis);
            //生成操作数据的id
            String id = JsonUtil.toJsonString(farmRecordsDiagnosis.getId());
            //todo 生成日志记录
            sysLogsService.createLogs(LogsEnum.UPDATE, FarmRecordsTableEnum.FARM_RECORDS_DIAGNOSIS.getTableName(),id,beforeJson,afterJson, UserUtil.getUserId());*/
            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    @Override
    public Integer updateEarNumberByCowRelateId(Long cowRelateId, String ear_tag_number) {
        Integer con = 0;
        if (!Strings.isNullOrEmpty(ear_tag_number) && cowRelateId != null) {
            String earNumber = "[]";
            try {
                earNumber = (String) objectMapper.writeValueAsString(Lists.newArrayList(ear_tag_number));
            } catch (Exception e) {
                e.printStackTrace();
            }

            Map<String,Object> map = Maps.newHashMap();
            map.put("ear_tag_number_json",earNumber);
            map.put("cow_relate_id",cowRelateId);
            con = farmRecordsDiagnosisMapper.updateEarNumberByCowRelateId(map);
        }
        return con;
    }
}
